<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理系统</title>
    <script src="js/stu/jquery.js"></script>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2ecc71;
            --danger-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
            --border-radius: 4px;
            --box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f7fa;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        h1 {
            color: var(--dark-color);
            font-size: 24px;
        }

        .search-box {
            background: #f8f9fa;
            padding: 15px;
            border-radius: var(--border-radius);
            margin-bottom: 20px;
            display: flex;
            gap: 15px;
            align-items: flex-end;
        }

        .form-group {
            flex: 1;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }

        input, select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 14px;
            transition: border-color 0.3s;
        }

        input:focus, select:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        button {
            padding: 8px 16px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-success {
            background-color: var(--secondary-color);
            color: white;
        }

        .btn-success:hover {
            background-color: #27ae60;
        }

        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }

        .btn-danger:hover {
            background-color: #c0392b;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: var(--light-color);
            font-weight: 600;
            color: var(--dark-color);
        }

        tr:hover {
            background-color: #f8f9fa;
        }

        .pagination {
            display: flex;
            list-style: none;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination li {
            margin: 0 5px;
            cursor: pointer;
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            transition: all 0.3s;
        }

        .pagination li:hover {
            background-color: #f8f9fa;
        }

        .pagination li.active {
            background-color: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-buttons button {
            padding: 5px 10px;
            font-size: 13px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            width: 50%;
            max-width: 500px;
            animation: modalopen 0.3s;
        }

        @keyframes modalopen {
            from { opacity: 0; transform: translateY(-50px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .modal-header h3 {
            color: var(--dark-color);
        }

        .close {
            font-size: 24px;
            font-weight: bold;
            color: #aaa;
            cursor: pointer;
        }

        .close:hover {
            color: #333;
        }

        .modal-body {
            margin-bottom: 20px;
        }

        .modal-footer {
            text-align: right;
        }

        .no-data {
            text-align: center;
            padding: 20px;
            color: #777;
        }

        @media (max-width: 768px) {
            .search-box {
                flex-direction: column;
                align-items: stretch;
            }

            .modal-content {
                width: 90%;
            }
        }


        /* 分配课程模态框特定样式 - 美化版 */
        #assignCoursesModal .modal-content {
            width: 65%;
            max-width: 700px;
        }


        .course-list {
            max-height: 300px;
            overflow-y: auto;
            margin-top: 10px;
            border-radius: var(--border-radius);
        }

        .course-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            transition: all 0.2s;
        }

        .course-item:hover {
            background-color: #f8fafc;
            transform: translateX(2px);
        }

        .course-checkbox {
            margin-right: 15px;
            width: 18px;
            height: 18px;
            accent-color: var(--secondary-color);
        }



        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 滚动条样式 */
        .course-list::-webkit-scrollbar {
            width: 6px;
        }

        .course-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .course-list::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        .course-list::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            #assignCoursesModal .modal-content {
                width: 90%;
                max-width: none;
            }

            .course-item {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>学生信息管理系统</h1>
        <button class="btn-success" onclick="addStudent()">新增学生</button>
    </div>

    <div class="search-box">
        <div class="form-group">
            <label for="searchName">姓名</label>
            <input type="text" id="searchName" placeholder="输入学生姓名">
        </div>
        <div class="form-group">
            <label for="searchGender">性别</label>
            <select id="searchGender">
                <option value="">所有性别</option>
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
        </div>
        <button class="btn-primary" id="searchBtn">搜索</button>
    </div>

    <table id="studentTable">
        <thead>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过AJAX动态加载 -->
        </tbody>
    </table>

    <div class="pagination-container">
        <ul class="pagination" id="pagination">
            <!-- 分页将通过AJAX动态生成 -->
        </ul>
    </div>
</div>

<!-- 新增学生模态框 -->
<div id="addRoleModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>新增学生</h3>
            <span class="close" onclick="closeAddRoleStudent()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="addRoleForm">
                <div class="form-group">
                    <label for="newname">姓名</label>
                    <input type="text" id="newname" name="name" required>
                </div>
                <div class="form-group">
                    <label for="newgender">性别</label>
                    <select id="newgender" name="gender" required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="newbirthday">生日</label>
                    <input type="date" id="newbirthday" name="birthday" required>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn-danger" onclick="closeAddRoleStudent()">取消</button>
            <button class="btn-success" onclick="submitAddRole()">保存</button>
        </div>
    </div>
</div>

<!-- 编辑学生模态框 -->
<div id="editRoleModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>编辑学生信息</h3>
            <span class="close" onclick="closeEditRoleStudent()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="editRoleForm">
                <input type="hidden" id="editStudentNo" name="studentNo">
                <div class="form-group">
                    <label for="editname">姓名</label>
                    <input type="text" id="editname" name="name" required>
                </div>
                <div class="form-group">
                    <label for="editgender">性别</label>
                    <select id="editgender" name="gender" required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editbirthday">生日</label>
                    <input type="date" id="editbirthday" name="birthday" required>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn-danger" onclick="closeEditRoleStudent()">取消</button>
            <button class="btn-success" onclick="submitEditStudent()">保存</button>
        </div>
    </div>
</div>

<!-- 分配课程模态框 -->
<div id="assignCoursesModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>分配课程</h3>
            <span class="close" onclick="closeAssignCoursesModal()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="assignCoursesForm">
                <input type="hidden" id="assignStudentNo">
                <div class="form-group">
                    <label>学生姓名: <span id="assignStudentName"></span></label>
                </div>
                <div class="form-group">
                    <label>当前已选课程:</label>
                    <div id="currentCourses" class="current-courses">加载中...</div>
                </div>
                <div class="form-group">
                    <label>选择课程:</label>
                    <div id="courseCheckboxes" class="course-list">
                        <!-- 课程复选框将在这里动态加载 -->
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn-danger" onclick="closeAssignCoursesModal()">取消</button>
            <button class="btn-success" onclick="submitAssignCourses()">确认分配</button>
        </div>
    </div>
</div>

<script>
    let currentPage = 1;
    let allCourses = []; // 存储所有课程数据

    $(document).ready(function() {
        // 默认加载第一页数据
        loadStudentData(1);
        loadAllCourses();

        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            loadStudentData(1);
        });

        // 分页点击事件
        $(document).on('click', '.page-item', function() {
            const page = $(this).data('page');
            if (page) {
                loadStudentData(page);
            }
        });
    });

    // 加载学生数据
    function loadStudentData(page) {
        currentPage = page;
        const name = $('#searchName').val();
        const gender = $('#searchGender').val();

        $.ajax({
            url: '/student/pageStudent',
            type: 'GET',
            data: {
                current: page,
                size: 10,
                name: name,
                gender: gender
            },
            dataType: 'json',
            success: function(response) {
                renderTable(response.records);
                renderPagination(response.current, response.pages);
            },
            error: function(xhr, status, error) {
                console.error('加载数据失败:', error);
                alert('加载数据失败，请稍后重试');
            }
        });
    }

    // 渲染表格数据
    function renderTable(records) {
        const tbody = $('#studentTable tbody');
        tbody.empty();

        if (records.length === 0) {
            tbody.append('<tr><td colspan="5" class="no-data">暂无数据</td></tr>');
            return;
        }

        records.forEach(function(student) {
            const genderDisplay = student.gender === '男' ? '男' : '女';
            const birthday = student.birthday ? student.birthday : '无';

            const row = `
                <tr>
                    <td>${student.studentNo}</td>
                    <td>${student.name}</td>
                    <td>${genderDisplay}</td>
                    <td>${birthday}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn-primary" onclick="editStudent(${student.studentNo}, '${student.name}', '${student.gender}', '${student.birthday}')">修改</button>
                            <button class="btn-success" onclick="openAssignCoursesModal(${student.studentNo}, '${student.name}')">分配课程</button>
                            <button class="btn-danger" onclick="deleteStudent(${student.studentNo})">删除</button>
                        </div>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    // 渲染分页
    function renderPagination(currentPage, totalPages) {
        const pagination = $('#pagination');
        pagination.empty();

        if (totalPages <= 1) return;

        // 上一页按钮
        if (currentPage > 1) {
            pagination.append(`
                <li class="page-item" data-page="${currentPage - 1}">上一页</li>
            `);
        }

        // 页码按钮
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
            pagination.append('<li class="page-item" data-page="1">1</li>');
            if (startPage > 2) {
                pagination.append('<li class="page-item disabled">...</li>');
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === currentPage ? 'active' : '';
            pagination.append(`
                <li class="page-item ${activeClass}" data-page="${i}">${i}</li>
            `);
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                pagination.append('<li class="page-item disabled">...</li>');
            }
            pagination.append(`<li class="page-item" data-page="${totalPages}">${totalPages}</li>`);
        }

        // 下一页按钮
        if (currentPage < totalPages) {
            pagination.append(`
                <li class="page-item" data-page="${currentPage + 1}">下一页</li>
            `);
        }
    }

    // 新增学生相关函数
    function addStudent() {
        $('#addRoleForm')[0].reset();
        $('#addRoleModal').show();
    }

    function closeAddRoleStudent() {
        $('#addRoleModal').hide();
    }

    function submitAddRole() {
        const name = $('#newname').val();
        const birthday = $('#newbirthday').val();
        const gender = $('#newgender').val();

        $.ajax({
            url: '/student/addStudent',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                name: name,
                birthday: birthday,
                gender: gender
            }),
            success: function(response) {
                alert(response.msg);
                closeAddRoleStudent();
                loadStudentData(currentPage);
            },
            error: function() {
                alert('新增失败，请检查网络或服务是否正常');
            }
        });
    }

    // 编辑学生相关函数
    function editStudent(studentNo, name, gender, birthday) {
        $('#editStudentNo').val(studentNo);
        $('#editname').val(name);
        $('#editgender').val(gender);
        $('#editbirthday').val(birthday || '');
        $('#editRoleModal').show();
    }

    function closeEditRoleStudent() {
        $('#editRoleModal').hide();
    }

    function submitEditStudent() {
        const student = {
            studentNo: $('#editStudentNo').val(),
            name: $('#editname').val(),
            gender: $('#editgender').val(),
            birthday: $('#editbirthday').val()
        };

        $.ajax({
            url: '/student/updateStudent',
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function(response) {
                alert(response.msg);
                if (response.msg === 'success') {
                    closeEditRoleStudent();
                    loadStudentData(currentPage);
                }
            },
            error: function() {
                alert('修改失败，请检查网络或服务是否正常');
            }
        });
    }

    // 删除学生
    function deleteStudent(studentNo) {
        if (confirm('确定要删除该学生吗？')) {
            $.ajax({
                url: '/student/deleteStudent',
                method: 'DELETE',
                data: {
                    studentNo: studentNo
                },
                success: function(response) {
                    alert(response.msg);
                    if (response.msg === 'success') {
                        loadStudentData(currentPage);
                    }
                },
                error: function() {
                    alert('删除失败，请检查网络或服务是否正常');
                }
            });
        }
    }

    // 加载所有课程
    function loadAllCourses() {
        $.ajax({
            url: '/student/findAllCourse',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    allCourses = response.data;
                } else {
                    console.error('加载课程列表失败:', response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error('加载课程列表失败:', error);
            }
        });
    }

    // 打开分配课程模态框
    function openAssignCoursesModal(studentNo, studentName) {
        $('#assignStudentNo').val(studentNo);
        $('#assignStudentName').text(studentName);

        // 加载课程复选框
        renderCourseCheckboxes(studentNo);

        // 加载当前已选课程
        loadCurrentCourses(studentNo);

        $('#assignCoursesModal').show();
    }

    // 渲染课程复选框
    function renderCourseCheckboxes(studentNo) {
        const container = $('#courseCheckboxes');
        container.empty();

        allCourses.forEach(course => {
            container.append(`
                <div class="course-item">
                    <input type="checkbox" class="course-checkbox"
                           id="course-${course.courseNo}"
                           value="${course.courseNo}">
                    <label for="course-${course.courseNo}">
                        ${course.courseName} (${course.courseNo})
                    </label>
                </div>
            `);
        });
    }

    // 加载当前已选课程
    function loadCurrentCourses(studentNo) {
        const container = $('#currentCourses');
        container.text('加载中...');

        $.ajax({
            url: '/student/getCourseByStudentId',
            method: 'GET',
            data: { studentNo: studentNo },
            success: function(response) {
                if (response.success) {
                    if (response.data && response.data.length > 0) {
                        // 显示已选课程名称
                        const selectedNames = allCourses
                            .filter(c => response.data.includes(c.courseNo))
                            .map(c => c.courseName)
                            .join(', ');
                        container.text(selectedNames || '无');

                        // 标记已选课程
                        response.data.forEach(courseId => {
                            $(`#course-${courseId}`).prop('checked', true);
                        });
                    } else {
                        container.text('未选课');
                    }
                } else {
                    container.text('加载失败');
                }
            },
            error: function(xhr, status, error) {
                container.text('加载失败');
                console.error('加载学生课程失败:', error);
            }
        });
    }

    // 关闭分配课程模态框
    function closeAssignCoursesModal() {
        $('#assignCoursesModal').hide();
    }

    // 提交分配课程
    function submitAssignCourses() {
        const studentNo = $('#assignStudentNo').val();
        const selectedCourses = [];

        $('.course-checkbox:checked').each(function() {
            selectedCourses.push($(this).val());
        });

        if (selectedCourses.length === 0) {
            alert('请至少选择一门课程');
            return;
        }

        // 构建符合@RequestParam List<Integer>格式的URL
        let url = `/student/assignCourses?studentNo=${studentNo}`;
        selectedCourses.forEach(courseNo => {
            url += `&courseNo=${courseNo}`;
        });

        $.ajax({
            url: url,
            type: 'PUT',
            success: function(response) {
                if (response.success) {
                    alert('课程分配成功');
                    closeAssignCoursesModal();
                    loadCurrentCourses(studentNo); // 刷新当前课程显示
                } else {
                    alert(response.message || '分配失败');
                }
            },
            error: function(xhr, status, error) {
                alert('分配课程失败: ' + (xhr.responseJSON?.message || error));
            }
        });
    }
</script>
</body>
</html>